import React, { useEffect, useState } from "react";
import { Button, Form, Radio, Input, message, Select } from "antd";
import {
  getSexEnumOptions,
  getColorEnumOptions,
} from "../../store/global-data.js";
import http from "../../api/index.js";
import { useNavigate } from "react-router-dom";
import { useSearchParams, useParams } from "react-router-dom";

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 8 },
};

const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};

/**
 * 添加编辑页
 * @returns
 */
export default function Edit() {
  const sexOptions = getSexEnumOptions();
  const colorOptions = getColorEnumOptions();

  const [search, setSearch] = useSearchParams();
  //   const id = search.get("id");

  const { id } = useParams();

  const navigate = useNavigate();

  const initialValues = {
    name: "",
    sex: sexOptions[0].value,
    color: colorOptions[0].value,
  };

  const [form] = Form.useForm();

  const onReset = () => {
    form.resetFields();
  };

  const onFinish = async (data) => {
    console.log("Success:", data);

    if (id) {
      await http.post("/updateUser", { ...data, id });
    } else {
      await http.post("/addUser", data);
    }

    message.success("操作成功");

    navigate("/list");
  };

  // 初始化
  async function initData() {
    const res = await http.get("/getUser", { params: { id } });
    console.log(res);

    // for (const key in initialValues) {
    //   initialValues[key] = res[key];
    form.setFieldsValue(res);
    // }
  }

  useEffect(() => {
    initData();
  }, []);

  return (
    <Form
      name="form"
      initialValues={initialValues}
      form={form}
      {...layout}
      onFinish={onFinish}
    >
      {/* 姓名 */}
      <Form.Item name="name" label="姓名" rules={[{ required: true }]}>
        <Input placeholder="输入姓名" allowClear />
      </Form.Item>

      {/* 性别 */}
      <Form.Item name="sex" label="性别" rules={[{ required: true }]}>
        <Radio.Group options={sexOptions}></Radio.Group>
      </Form.Item>

      {/* 颜色 */}
      <Form.Item name="color" label="颜色" rules={[{ required: true }]}>
        <Select placeholder="选择颜色" options={colorOptions}></Select>
      </Form.Item>

      <Form.Item {...tailLayout}>
        <Button htmlType="button" onClick={onReset}>
          重置
        </Button>

        <Button type="primary" htmlType="submit" style={{ marginLeft: "10px" }}>
          提交
        </Button>
      </Form.Item>
    </Form>
  );
}
